package com.meichis.yndms.hybrid;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ProgressBar;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Locale;

public class MCWebView extends WebView {
    public static final String TAG = "MCWebView";
    private HybridInterface hybrid;
    public ProgressBar progressbar;
    public String URL;
    public boolean isloadFailed = false;

    public static Context getFixedContext(Context context) {
        if (Build.VERSION.SDK_INT >= 21 && Build.VERSION.SDK_INT < 23) { // Android Lollipop 5.0 & 5.1
            return context.createConfigurationContext(new Configuration());
        }
        return context;
    }

    public MCWebView(Context context) {
        super(getFixedContext(context));

        if (HybridInterface.class.isInstance(context)) {
            this.hybrid = (HybridInterface) context;
        } else {
            Log.d(TAG, "Your activity must implement HybridInterface to work");
        }
        progressbar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
        progressbar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 3, 0, 0));

        // ClipDrawable d = new ClipDrawable(new ColorDrawable(Color.BLUE),
        // Gravity.LEFT, ClipDrawable.HORIZONTAL);
        // progressbar.setProgressDrawable(d);
        addView(progressbar);
        this.loadConfiguration();
        this.setup();

    }

    /**
     * Constructor.
     *
     * @param context
     * @param attrs
     */
    @SuppressWarnings("deprecation")
    public MCWebView(Context context, AttributeSet attrs) {
        super(getFixedContext(context), attrs);
        if (HybridInterface.class.isInstance(context)) {
            this.hybrid = (HybridInterface) context;
        } else {
            Log.d(TAG, "Your activity must implement HybridInterface to work");
        }
        progressbar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
        // ClipDrawable d = new ClipDrawable(new ColorDrawable(Color.BLUE),
        // Gravity.LEFT, ClipDrawable.HORIZONTAL);
        // progressbar.setProgressDrawable(d);
        progressbar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 3, 0, 0));
        addView(progressbar);
        this.setWebChromeClient(new MCSChromeClient(this.hybrid));
        this.setWebViewClient(new MCSWebViewClient());
        this.loadConfiguration();
        this.setup();
    }

    /**
     * Constructor.
     *
     * @param context
     * @param attrs
     * @param defStyle
     */
    public MCWebView(Context context, AttributeSet attrs, int defStyle) {
        super(getFixedContext(context), attrs, defStyle);
        if (HybridInterface.class.isInstance(context)) {
            this.hybrid = (HybridInterface) context;
        } else {
            Log.d(TAG, "Your activity must implement HybridInterface to work");
        }
        progressbar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
        progressbar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 3, 0, 0));
        // ClipDrawable d = new ClipDrawable(new ColorDrawable(Color.BLUE),
        // Gravity.LEFT, ClipDrawable.HORIZONTAL);
        // progressbar.setProgressDrawable(d);
        addView(progressbar);
        this.setWebChromeClient(new MCSChromeClient(this.hybrid));
        this.loadConfiguration();
        this.setup();
    }

    /**
     * Constructor.
     *
     * @param context
     * @param attrs
     * @param defStyle
     * @param privateBrowsing
     */
    @SuppressWarnings("deprecation")
    @TargetApi(11)
    public MCWebView(Context context, AttributeSet attrs, int defStyle, boolean privateBrowsing) {
        super(getFixedContext(context), attrs, defStyle, privateBrowsing);
        if (HybridInterface.class.isInstance(context)) {
            this.hybrid = (HybridInterface) context;
        } else {
            Log.d(TAG, "Your activity must implement HybridInterface to work");
        }
        progressbar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
        progressbar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 3, 0, 0));
        // ClipDrawable d = new ClipDrawable(new ColorDrawable(Color.BLUE),
        // Gravity.LEFT, ClipDrawable.HORIZONTAL);
        // progressbar.setProgressDrawable(d);
        addView(progressbar);
        this.setWebChromeClient(new MCSChromeClient(this.hybrid));
        this.setWebViewClient(new MCSWebViewClient());
        this.loadConfiguration();
        this.setup();
    }

    private void loadConfiguration() {

        if ("true".equals(this.getProperty("Fullscreen", "false"))) {
            this.hybrid.getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
            this.hybrid.getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
    }

    public String getProperty(String name, String defaultValue) {
        try {

            Bundle bundle = this.hybrid.getActivity().getIntent().getExtras();
            if (bundle == null) {
                return defaultValue;
            }
            name = name.toLowerCase(Locale.getDefault());
            Object p = bundle.get(name);
            if (p == null) {
                return defaultValue;
            }

            return p.toString();
        } catch (Exception e) {
            // TODO: handle exception
        }
        return "";
    }

    @SuppressLint({"SetJavaScriptEnabled", "WrongConstant"})
    @SuppressWarnings("deprecation")
    private void setup() {
        this.setInitialScale(0);
        this.setVerticalScrollBarEnabled(false);
        this.setHorizontalScrollBarEnabled(false);
        this.setScrollBarStyle(View.GONE);
        this.requestFocusFromTouch();

        // Enable JavaScript
        WebSettings settings = this.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setLoadsImagesAutomatically(true);
        settings.setBuiltInZoomControls(false);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setSupportMultipleWindows(true);

        // Set the nav dump for HTC 2.x devices (disabling for ICS, deprecated
        // entirely for Jellybean 4.2)
        try {
            Method gingerbread_getMethod = WebSettings.class.getMethod("setNavDump", new Class[]{boolean.class});

            String manufacturer = android.os.Build.MANUFACTURER;
            Log.d(TAG, "MCWebView is running on device made by: " + manufacturer);
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB && android.os.Build.MANUFACTURER.contains("HTC")) {
                gingerbread_getMethod.invoke(settings, true);
            }
        } catch (NoSuchMethodException e) {
            Log.d(TAG, "We are on a modern version of Android, we will deprecate HTC 2.3 devices in 2.8");
        } catch (IllegalArgumentException e) {
            Log.d(TAG, "Doing the NavDump failed with bad arguments");
        } catch (IllegalAccessException e) {
            Log.d(TAG, "This should never happen: IllegalAccessException means this isn't Android anymore");
        } catch (InvocationTargetException e) {
            Log.d(TAG, "This should never happen: InvocationTargetException means this isn't Android anymore.");
        }

        settings.setSaveFormData(false);
        settings.setSavePassword(false);
        //
        // if (android.os.Build.VERSION.SDK_INT >
        // android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
        // Level16Apis.enableUniversalAccess(settings);

        settings.setDomStorageEnabled(true);

        settings.setGeolocationEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        // Enable AppCache
        // Fix for CB-2282
        try {
            settings.setAppCacheMaxSize(5 * 1048576);
            String pathToCache = this.hybrid.getActivity().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
            settings.setAppCachePath(pathToCache);
            settings.setAppCacheEnabled(true);
        } catch (Exception e) {
            // TODO: handle exception
        }

        // Fix for CB-1405
        // Google issue 4641
        this.getSettings().getUserAgentString();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
        setBackgroundColor(Color.rgb(240, 240, 240));
        // end CB-1405
        if (Build.VERSION.SDK_INT >= 17)
            this.addJavascriptInterface(new JavaScriptInterface(this.getContext(), this, hybrid), "MCSAPPIF");

    }

    public void sendResult(Object result, String FUNCCallBack, String ControlID) {
        if (TextUtils.isEmpty(ControlID.toString()))

            this.loadUrl("javascript:" + FUNCCallBack + "('" + result.toString() + "')");
        else
            this.loadUrl("javascript:" + FUNCCallBack + "('" + ControlID + "','" + result.toString() + "')");
    }

    public boolean backHistory() {

        // Check webview first to see if there is a history
        // This is needed to support curPage#diffLink, since they are added to
        // appView's history, but not our history url array (JQMobile behavior)
        if (super.canGoBack()) {
            super.goBack();

            return true;
        }
        return false;
    }

    // @TargetApi(16)
    // private static class Level16Apis {
    // static void enableUniversalAccess(WebSettings settings) {
    // settings.setAllowUniversalAccessFromFileURLs(true);
    // }
    // }

    /**
     * 计算webView内容的真实宽度
     * @return
     */
    public int getMeasureContentWidth() {
        return computeHorizontalScrollRange();
    }

    /**
     * 计算webView内容的真实高度
     * @return
     */
    public int getMeasureContentHeight() {
        return computeVerticalScrollRange();
    }
}
